<?php

class FnSvc
{
    const API_URL = 'https://exam-anubis.ele.me/anubis-webapi';
    const APP_ID = '04bdf897-12e9-42c0-904f-225e30e2bff4';    //填入正确的app_id
    const SECRET_KEY = 'a9555ac9-cf86-4077-abc1-2668722121eb';
    const NOTIFY_URL = 'http://t6.ueu.cn//Fn/notify';

    /*
        蜂鸟平台：
        地址：https://open.ele.me/documents?to=%2Fdocument%2Fpage%2FopenPlatform
        账号：kfyaoapp@163.com
        密码：Kf123456
    */

      public function batchAudit(){
        $str = $_POST['id'];
        foreach ($str as $key=>$val){
            $sql = "update kfsy_pingtai.kf_drugstore_chain set ZT=2 where YID=$val and ZT=1";
            $arr = DB::update_db(1, $sql);
        }

        exit( json_encode(array("code"=>200,"msg"=>"'ok'")));
    }

    public function DLOG($log_content='', $log_level='', $log_name='')
    { 

        if(empty($log_level)||empty($log_content))
            return;
        
        
        if(empty($log_name) && $log_level == 'run')
            $log_name = 'run';

        $log_dir = "/mnt/logs/";
        $log_file = $log_dir.$log_name.".".date('Y-m-d').".log";
        
        //默认每行日志必写的内容，统一在这里处理
        // ZHANGXI 2015/1/7 for regular
        $time = sprintf("%8s.%03d",date('H:i:s'),floor(microtime()*1000));
        //$time = date('H:i:s').".".floor(microtime()*1000);
        $ip = sprintf("%15s",$_SERVER["REMOTE_ADDR"]);

        $id =   "req-Fn";

        $path_arr = explode("/", $_SERVER['REQUEST_URI']);

        $content_prefix = "[ ".$time." ".$ip." ".$id." ".$log_level." ".$path_arr[1]." ".$path_arr[2]." ] ";

        $fp = fopen($log_file, 'a+');
        fwrite($fp, $content_prefix.$log_content." [".getmypid()."]\n");
        fclose($fp);
        return true;
    }

    /*
     * 创建门店
     * */
    public function createStore($data,$id,$ptid){
        $url =self::API_URL."/v2/chain_store";
        $appid = self::APP_ID;
        $salt =self::getCode();
        $json = json_encode($data);
        $urlencodeData = urlencode($json);
        $token =  $this->requestToken();
        $sign = self::generateBusinessSign($appid, $token, $urlencodeData, $salt);
        $arr = json_encode(array(
            'app_id'=>$appid,
            'salt'=> $salt,
            'data'=>$urlencodeData,
            'signature'=>$sign
        ));
        $res = json_decode(self::doPost($url,$arr),true);
        if($res['code']==200){
            $sql = "insert into kfsy_pingtai.kf_drugstore_chain(PTID,YID,ZT)VALUES ($ptid,$id,1)";
            $arr = DB::insert_db(1, $sql);
        }else{
            $sql = "insert into kfsy_pingtai.kf_drugstore_chain(PTID,YID,ZT)VALUES ($ptid,$id,0)";
            $arr = DB::insert_db(1, $sql);
        }
        return $res;
    }

    /*
        创建订单信息
    */

    public function getCode(){
        return mt_rand(1000, 9999);
    }

    public function requestToken($salt="") {
        // 获取签名
        $salt = mt_rand(1000, 9999);
        $sig = self::generateSign(self::APP_ID, $salt, self::SECRET_KEY);
        $url = "https://exam-anubis.ele.me/anubis-webapi/get_access_token";
        $tokenStr = self::doGet($url, array('app_id' => self::APP_ID, 'salt' => $salt, 'signature' => $sig));
        // echo $tokenStr;
        // 获取token
        $token = json_decode($tokenStr, true);
        return $token['data']['access_token'];

    }


    public static function generateSign($appId, $salt, $secretKey) {
        $seed = 'app_id=' . $appId . '&salt=' . $salt . '&secret_key=' . $secretKey;
        return md5(urlencode($seed));
    }

    public static function generateBusinessSign($appId, $token, $urlencodeData, $salt)
    {
        $seed = 'app_id=' . $appId . '&access_token=' . $token
            . '&data=' . $urlencodeData . '&salt=' . $salt;
        return md5($seed);
    }

    public static function doPost($url, $param, $method = "POST")
    {
        // echo 'Request url is ' . $url . PHP_EOL;
        if (empty($url) or empty($param)) {
            throw new InvalidArgumentException('Params is not of the expected type');
        }

        // 验证url合法性
//        if (!filter_var($url, FILTER_VALIDATE_URL)) {
//            throw new InvalidArgumentException('Url is not valid');
//        }

        if (!empty($param) and is_array($param)) {
            $param = urldecode(json_encode($param));
        } else {
            // $param = urldecode(strval($param));
            $param = strval($param);
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        // curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);     //  不进行ssl 认证

        if (strcmp($method, "POST") == 0) {  // POST 操作
            curl_setopt($ch, CURLOPT_POST, true);
        } else if (strcmp($method, "DELETE") == 0) { // DELETE操作
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        } else {
            throw new InvalidArgumentException('Please input correct http method, such as POST or DELETE');
        }

        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: Application/json'));
        $result = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if (!empty($result) and $code == '200') {
            return $result;
        }
        return false;
    }





    public static function doGet($url, $param = null)
    {
        if (empty($url) or (!empty($param) and !is_array($param))) {
            throw new InvalidArgumentException('Params is not of the expected type');
        }
        // 验证url合法性
//        if (!filter_var($url, FILTER_VALIDATE_URL)) {
//            throw new InvalidArgumentException('Url is not valid');
//        }

        if (!empty($param)) {
            $url = trim($url, '?') . '?' . http_build_query($param);
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);     //  不进行ssl 认证
        // curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        $result = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if (!empty($result) and $code == 200) {
            return $result;
        }
        return false;
    }


    /*
        创建订单
        https://open.ele.me/documents?to=%2Fdocument%2Fpage%2FtimelyDelivery
        params
            partner_order_code 订单编号
            partner_remark 订单备注
            order_add_time 下单时间(毫秒)
            order_remark 用户备注

            transport_info 商户门店信息
            payment_info 用户支付信息
            receiver_info 收货人信息
            items 商品信息
    */
    public function createOrder($partner_order_code = '', $partner_remark = '', $order_add_time = '', $order_remark = '', $transport_info = array(), $payment_info = array(), $receiver_info = array(), $items = array())
    {
        $data = array();
        $data['partner_order_code'] = $partner_order_code;
        $data['order_add_time'] = $order_add_time;

        if(empty($partner_remark) == false){
            $data['partner_remark'] = $partner_remark;
        }

        if(empty($order_remark) == false){
            $data['order_remark'] = $order_remark;
        }

        $data['notify_url'] = self::NOTIFY_URL; //回调地址,订单状态变更时会调用此接口传递状态信息
        $data['order_type'] = 1; //订单类型 1: 蜂鸟配送，支持90分钟内送达
        $data['transport_info'] = $transport_info;
        
        $data = array_merge($data, $payment_info);
        $data['goods_count'] = count($items);
        $data['receiver_info'] = $receiver_info;
        $data['items_json'] = $items;
        $data['order_weight'] = 0.5; //订单总重量（kg），营业类型选定为果蔬生鲜、商店超市、其他三类时必填，大于0kg并且小于等于6kg

        return $data;
    }

    /*
        获取订单信息
        https://open.ele.me/documents?to=%2Fdocument%2Fpage%2ForderQuery
        params
            partner_order_code 订单编号
    */
    public function getOrderInfo($partner_order_code = '')
    {
        $data = array();
        $data['partner_order_code'] = $partner_order_code;

        return $data;
    }

    /*
        取消订单
        https://open.ele.me/documents?to=%2Fdocument%2Fpage%2FsyncOrderCancel
        params
            partner_order_code 商户订单号
            order_cancel_code 订单取消编码（0:其他, 1:联系不上商户, 2:商品已经售完, 3:用户申请取消, 4:运力告知不配送 让取消订单, 5:订单长时间未分配, 6:接单后骑手未取件）
            order_cancel_description 订单取消描述（order_cancel_code为0时必填）
            order_cancel_time 订单取消时间（毫秒）
    */
    public function cancelOrder($partner_order_code = '', $order_cancel_code = 0, $order_cancel_description = '', $order_cancel_time = 0)
    {
        $data = array();
        $data['partner_order_code'] = $partner_order_code;
        $data['order_cancel_reason_code'] = 2; //订单取消原因代码(2:商家取消)
        $data['order_cancel_code'] = $order_cancel_code;
        $data['order_cancel_description'] = $order_cancel_description;
        $data['order_cancel_time'] = $order_cancel_time;

        return $data;
    }

    /*
        投诉订单
        https://open.ele.me/documents?to=%2Fdocument%2Fpage%2ForderComplaint
        params
            partner_order_code 商户订单号
            order_complaint_code 订单投诉编码（230:其他, 150:未保持餐品完整, 160:服务态度恶劣, 190:额外索取费用, 170:诱导收货人或商户退单, 140:提前点击送达, 210:虚假标记异常, 220:少餐错餐, 200:虚假配送, 130:未进行配送
            order_complaint_desc 订单投诉描述（order_complaint_code为230时必填）
            order_complaint_time 订单投诉时间（毫秒）
    */
    public function complaintOrder($partner_order_code = '', $order_complaint_code = 0, $order_complaint_desc = '', $order_complaint_time = 0)
    {
        $data = array();
        $data['partner_order_code'] = $partner_order_code;
        $data['order_complaint_code'] = $order_complaint_code;
        $data['order_complaint_desc'] = $order_complaint_desc;
        $data['order_complaint_time'] = $order_complaint_time;

        return $data;
    }

    /*
        发送配送信息到蜂鸟
        params
            data 配送信息对象(createOrder)
    */
    public function sendOrderToFn($data = array())
    {
        $this->DLOG("create_order : " . json_encode($data), "run", "fn_order");

        $url =self::API_URL."/v2/order";
        $appid = self::APP_ID;

        $salt =self::getCode();

        $json = json_encode($data);

        $urlencodeData = urlencode($json);
        $token =  $this->requestToken();

        $sign = self::generateBusinessSign($appid, $token, $urlencodeData, $salt);

        $arr = json_encode(array(
            'app_id'=>$appid,
            'salt'=> $salt,
            'data'=>$urlencodeData,
            'signature'=>$sign
        ));

        $res = json_decode(self::doPost($url, $arr),true);

        $log = array(
            "partner_order_code" => $data['partner_order_code'],
            "res" => $res
        );
        $this->DLOG("create_order_res : " . json_encode($log), "run", "fn_order");
        return $res;
    }

    /*
        从蜂鸟获取配送信息
        params
            data 查询配送信息对象(getOrder)
    */
    public function getOrderInfoByFn($data = array())
    {
        $this->DLOG("get_order : " . json_encode($data), "run", "fn_order");

        $url =self::API_URL."/v2/order/query";
        $appid = self::APP_ID;

        $salt =self::getCode();

        $json = json_encode($data);

        $urlencodeData = urlencode($json);
        $token =  $this->requestToken();

        $sign = self::generateBusinessSign($appid, $token, $urlencodeData, $salt);

        $arr = json_encode(array(
            'app_id'=>$appid,
            'salt'=> $salt,
            'data'=>$urlencodeData,
            'signature'=>$sign
        ));

        $res = json_decode(self::doPost($url, $arr),true);

        $log = array(
            "partner_order_code" => $data['partner_order_code'],
            "res" => $res
        );
        $this->DLOG("get_order_res : " . json_encode($log), "run", "fn_order");
        return $res;
    }

    /*
        从蜂鸟配送取消订单
        params
            data 取消订单对象(cancelOrder)
    */
    public function cancelOrderToFn($data = array())
    {
        $this->DLOG("cancel_order : " . json_encode($data), "run", "fn_order");

        $url =self::API_URL."/v2/order/cancel";
        $appid = self::APP_ID;

        $salt =self::getCode();

        $json = json_encode($data);

        $urlencodeData = urlencode($json);
        $token =  $this->requestToken();

        $sign = self::generateBusinessSign($appid, $token, $urlencodeData, $salt);

        $arr = json_encode(array(
            'app_id'=>$appid,
            'salt'=> $salt,
            'data'=>$urlencodeData,
            'signature'=>$sign
        ));

        $res = json_decode(self::doPost($url, $arr),true);

        $log = array(
            "partner_order_code" => $data['partner_order_code'],
            "res" => $res
        );
        $this->DLOG("cancel_order_res : " . json_encode($log), "run", "fn_order");
        return $res;
    }

    /*
        向蜂鸟投诉订单
        params
            data 投诉订单对象(complaintOrder)
    */
    public function complaintOrderToFn($data = array())
    {
        $this->DLOG("complaint_order : " . json_encode($data), "run", "fn_order");

        $url =self::API_URL."/v2/order/complaint";
        $appid = self::APP_ID;

        $salt =self::getCode();

        $json = json_encode($data);

        $urlencodeData = urlencode($json);
        $token =  $this->requestToken();

        $sign = self::generateBusinessSign($appid, $token, $urlencodeData, $salt);

        $arr = json_encode(array(
            'app_id'=>$appid,
            'salt'=> $salt,
            'data'=>$urlencodeData,
            'signature'=>$sign
        ));

        $res = json_decode(self::doPost($url, $arr),true);

        $log = array(
            "partner_order_code" => $data['partner_order_code'],
            "res" => $res
        );
        $this->DLOG("complaint_order_res : " . json_encode($log), "run", "fn_order");
        return $res;
    }

    /*
        生成商户信息
        params
            transport_name 门店名称
            transport_address 取货点地址 
            transport_longitude 取货点经度，取值范围0～180
            transport_latitude 取货点纬度，取值范围0～90
            transport_tel 取货点联系方式, 只支持手机号,400开头电话以及座机号码
            transport_remark 取货点备注
    */
    public static function createTransportInfo($transport_name = '', $transport_address = '', $transport_longitude = '', $transport_latitude = '', $transport_tel = '', $transport_remark = '')
    {
        $data = array();
        $data['transport_name'] = $transport_name;
        $data['transport_address'] = $transport_address;
        $data['transport_longitude'] = $transport_longitude;
        $data['transport_latitude'] = $transport_latitude;
        $data['position_source'] = 3; //取货点经纬度来源, 1:腾讯地图, 2:百度地图, 3:高德地图
        $data['transport_tel'] = $transport_tel;
        $data['transport_remark'] = $transport_remark;

        return $data;
    }

    /*
        订单支付信息
        params
            order_total_amount 订单总金额（不包含商家的任何活动以及折扣的金额）
            order_actual_amount 客户需要支付的金额
            order_payment_status 订单支付状态 0:未支付 1:已支付
            is_invoiced 是否需要发票, 0:不需要, 1:需要
            invoice 发票抬头, 如果需要发票, 此项必填
    */
    public function createPaymentInfo($order_total_amount = 0, $order_actual_amount = 0, $order_payment_status = 0, $is_invoiced = 0, $invoice = '')
    {
        $data = array();
        $data['order_total_amount'] = $order_total_amount;
        $data['order_actual_amount'] = $order_actual_amount;
        $data['order_payment_status'] = $order_payment_status;
        $data['order_payment_method'] = 1; //订单支付方式 1:在线支付
        $data['is_agent_payment'] = 0; //是否需要ele代收 0:否
        $data['is_invoiced'] = $is_invoiced < 1 ? 0 : 1;
        if($data['is_invoiced'] > 0){
            $data['invoice'] = $invoice;
        }

        return $data;
    }

    /*
        收货人信息
        params
            receiver_name 收货人姓名
            receiver_primary_phone 收货人联系电话, 只支持手机号, 只支持手机号
            receiver_address 收货人地址
            receiver_longitude 收货人经度，取值范围0～180
            receiver_latitude 收货人纬度，取值范围0～90
    */
    public function createCustomerInfo($receiver_name = '', $receiver_primary_phone = '', $receiver_address = '', $receiver_longitude = '', $receiver_latitude = '')
    {
        $data = array();
        $data['receiver_name'] = $receiver_name;
        $data['receiver_primary_phone'] = $receiver_primary_phone;
        $data['receiver_address'] = $receiver_address;
        $data['receiver_longitude'] = $receiver_longitude;
        $data['receiver_latitude'] = $receiver_latitude;
        $data['position_source'] = 3; //收货人经纬度来源, 1:腾讯地图, 2:百度地图, 3:高德地图

        return $data;
    }

    /*
        商品信息
        params
            item_name 商品名称
            item_quantity 商品数量
            item_price 商品原价
            item_actual_price 商品实际支付金额
    */
    public function createProductInfo($item_name = '', $item_quantity = 0, $item_price = 0, $item_actual_price = 0)
    {
        $data = array();
        $data['item_name'] = $item_name;
        $data['item_quantity'] = $item_quantity;
        $data['item_price'] = $item_price;
        $data['item_actual_price'] = $item_actual_price;
        $data['is_need_package'] = 0;
        $data['is_agent_purchase'] = 0; //是否需要ele打包 0:否 1:是
        $data['is_need_package'] = 0; //是否代购 0:否

        return $data;
    }
}